#include <stdio.h>
#include "stdlib.h"
#include "ctype.h"
#include "cola_init.h"
#include "cola_device.h"
#include "cola_os.h"
#include "fml_touch.h"
#include "shell.h"

static cola_device_t *g_pDevTouch = NULL;
extern void logWrite(const char *fmt, ...);
static void fml_touch_read_version_info(void);

void fml_touch_init(void)
{
	g_pDevTouch = cola_device_find("touch");
    if(g_pDevTouch)
    {
        cola_device_open(g_pDevTouch, 0);
        fml_touch_read_version_info();
        cola_device_close(g_pDevTouch);
    }
}

int fml_touch_iic_write(uint8_t devAddr,uint8_t *buf,int len)
{
	int ret  =  0;
	cola_device_ctrl(g_pDevTouch, devAddr, NULL);
	ret = cola_device_write(g_pDevTouch, 0x00, buf, len);
	return ret;
}

int fml_touch_iic_read(uint8_t devAddr,uint8_t reg,uint8_t *buf,int len)
{
	int ret  =  0;
	cola_device_ctrl(g_pDevTouch, devAddr, NULL);
	ret = cola_device_write(g_pDevTouch, 0x00, &reg, 1);
	if(ret == 1)
		ret = cola_device_read(g_pDevTouch, 0x00, buf, len);
	return ret;
}

void fml_touch_iic_read_page_reg(uint32_t address,uint8_t *buf,int len)
{
	uint8_t pArray[5];

	pArray[0] = (address)&0xFF;
	pArray[1] = (address>>8)&0xFF;
	pArray[2] = (address>>16)&0xFF;
	pArray[3] = (address>>24)&0xFF;
	pArray[4] = 0x08;//setting
	cola_device_ctrl(g_pDevTouch, SLAVE_ADDR_TP, NULL);
	cola_device_write(g_pDevTouch,0,pArray,sizeof(pArray));
	cola_device_ctrl(g_pDevTouch, SLAVE_ADDR_TP, NULL);
	cola_device_read(g_pDevTouch,0,buf,len);
}

static void fml_touch_read_version_info(void)
{
	uint8_t buf[4];
	int len = sizeof(buf);
	unsigned long address = 0x200056a0;
	fml_touch_iic_read_page_reg(address,buf,len);//0x200056a0
	logWrite("read tp version[0x%08X]:",address);
	for (int i = 0; i < len; i++) {
		logWrite("%02X ", buf[i]);
	}
	logWrite("\r\n");
}

static unsigned long string_to_number(const char *str) {
    if (!str || *str == '\0') return -1;
    unsigned long result = 0;
    char *end_ptr;
    int base = 10;
    if (str[0] == '0' && tolower(str[1]) == 'x') {
    	base = 16;
    }
    result = strtoul(str, &end_ptr, base);
    return result;
}

#if 0
int touch_test(int argc, char *argv[]) {
	if (argc < 2) {
		logWrite("para length must greater than 2\r\n");
		return 0;
	}
	int i=0;
	uint8_t buf[10];
	unsigned long address = string_to_number(argv[1]);
	uint8_t len = string_to_number(argv[2]);
	if(len > sizeof(buf))
		len = sizeof(buf);
	fml_touch_iic_read_page_reg(address,buf,len);//0x200056a0
	logWrite("read address[0x%08X]:",address);
	for (i = 0; i < len; i++) {
		logWrite("%02X ", buf[i]);
	}
	logWrite("\r\n");
	return 0;
}
SHELL_EXPORT_CMD(SHELL_CMD_PERMISSION(0) | SHELL_CMD_TYPE(SHELL_TYPE_CMD_MAIN), touch_test, touch_test, touch_test);
#endif






